<template>
  <div>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索区 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary"
                     @click="AddDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-table :data="userList"
                border
                stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="邮箱" prop="umail"></el-table-column>
        <el-table-column label="电话" prop="uphone"></el-table-column>
        <el-table-column label="权限">
          <template slot-scope="scope">
            {{scope.row.uverify === 1 ? '超级管理员' : '普通用户'}}
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip effect="dark"
                        content="修改"
                        placement="top"
                        :enterable="false">
              <el-button type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click="showUpd(scope.row.userId)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark"
                        content="删除"
                        placement="top"
                        :enterable="false">
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="doDel(scope.row.userId)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="user.current"
                     :page-sizes="[3, 5, 10, 20]"
                     :page-size="user.size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户"
               :visible.sync="AddDialogVisible"
               width="50%"
               @close="AddDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="70px">
        <el-form-item label="邮箱"
                      prop="umail">
          <el-input v-model="addForm.umail"></el-input>
        </el-form-item>
        <el-form-item label="电话"
                      prop="uphone">
          <el-input v-model="addForm.uphone"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="upwd">
          <el-input v-model="addForm.upwd"></el-input>
        </el-form-item>
        <el-form-item label="权限"
                      prop="uverify">
          <el-select v-model="addForm.uverify"
                     placeholder="请选择">
            <el-option v-for="item in options"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户"
               :visible.sync="updDialogVisible"
               width="50%"
               @close="updDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="eidtForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="70px">
        <el-form-item label="邮箱"
                      prop="umail">
          <el-input v-model="eidtForm.umail"></el-input>
        </el-form-item>
        <el-form-item label="电话"
                      prop="uphone">
          <el-input v-model="eidtForm.uphone"></el-input>
        </el-form-item>
        <el-form-item label="权限"
                      prop="uverify">
          <el-select v-model="eidtForm.uverify"
                     placeholder="请选择">
            <el-option v-for="item in options"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="updDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="doUpd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        userList: [],
        user: {
          umail: '',
          uphone: '',
          current: 1,
          size: 5
        },
        total: 0,
        //控制对话框的显示与隐藏
        AddDialogVisible: false,
        updDialogVisible: false,
        addForm: {
          umail: '',
          uphone: '',
          upwd: '',
          uverify: ''
        },
        options: [
          {
            value: '0',
            label: '普通用户'
          },
          {
            value: '1',
            label: '超级管理员'
          }
        ],
        //添加表单的验证规则对象
        addFormRules: {
          uphone: [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
            {
              pattern: /^1[3/5/7/8/9]\d{9}$/,
              message: '请输入正确的电话号码',
              trigger: 'blur',
            },
          ],
          //验证密码是否合法
          upwd: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            {
              min: 6,
              max: 9,
              message: '长度在 6 到 9 个字符',
              trigger: ['blur', 'change'],
            },
          ],
          umail: [
            { required: true, message: '请输入电子邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
          ],
        },
        eidtForm: '',
        editFormRules: {
          //验证电话号码是否合法
          uphone: [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
            {
              pattern: /^1[3/5/7/8/9]\d{9}$/,
              message: '请输入正确的电话号码',
              trigger: 'blur',
            },
          ],
          umail: [
            { required: true, message: '请输入电子邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
          ],
        }
      }
    },
    created() {
      this.getUserList();
    },
    methods: {
      async getUserList() {
        let params = this.$qs.stringify({
          当前页: this.user.current,
          页面数量: this.user.size
        });
        let url = 'admin/user/selAllUser' + '?' + params;
        const {data: res} = await this.$axios.get(url);
        if(res.code !== 200){
          return this.$message.error(res.data);
        }
        this.userList = res.data.records;
        this.total = res.data.total;
      },
      //监听最新的 limit 改变事件
      handleSizeChange(newSize) {
        this.user.size = newSize
        this.getUserList()
      },
      //监听最新的 page 改变事件
      handleCurrentChange(newPage) {
        this.user.current = newPage
        this.getUserList()
      },
      //监听添加对话框的关闭事件
      AddDialogClosed() {
        this.$refs.addFormRef.resetFields();
      },
      //添加用户
      addUser() {
        let url = 'api/userLogin/addUser'
        let param = this.addForm
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) return;
          const { data: res } = await this.$axios.post(url, param);
          if (res.code !== 200) {
            return this.$message.error(res.data);
          }
          this.AddDialogVisible = false;
          this.getUserList();
          this.$message.success(res.data);
        })
      },
      async showUpd(user_id){
        let url = 'admin/user/selUser/' + user_id;
        const {data: res} = await this.$axios.get(url)
        if(res.code !== 200){
          return this.$message.error('查询新用户失败！');
        }
        this.eidtForm = res.data;
        this.updDialogVisible = true;
      },
      updDialogClosed(){
        this.$refs.eidtFormRef.resetFields();
      },
      doUpd(){
        let url = 'admin/user/updateUser/';
        let param = this.eidtForm;
        this.$refs.editFormRef.validate(async (valid) => {
          if (!valid) return;
          const { data: res } = await this.$axios.put(url, param);
          if (res.code !== 200) {
            return this.$message.error(res.data);
          }
          this.updDialogVisible = false;
          this.getUserList();
          this.$message.success(res.data);
        })
      },
      //根据id删除对应的信息
      async doDel(user_id) {
        //弹框询问
        const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(error => 
            error
          )
        //确认删除，返回值为字符串 confirm
        //取消删除，返回值为字符串 cancel
        if(res !== 'confirm'){
          return this.$message.info('您取消了删除！')
        }
        let url = 'admin/user/delUser/' + user_id;
        this.$axios.delete(url)
          .then(res => {
            if(res.data.code !== 200){
              return this.$message.error(res.data);
            }
            this.$message.success(res.data);
            this.getUserList();
          })
          .catch( err => 
            err
          )
      },
    }
  }
</script>

<style lang="less" scoped>
.el-col {
  display: flex;
  .el-button {
    margin-left: 15px;
  }
}
.el-table {
  border-radius: 2px;
}
</style>